﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Reflection;

namespace InfFront.InfoSources.Base.Design
{
    internal static class DesignTimeTools
    {
        public static IComponent CreateFreshComponent(this IDesignerHost host, Type type)
        {
            return CreateFreshComponent(host, type, null);
        }

        public static IComponent CreateFreshComponent(this IDesignerHost host, Type type, IContainer container)
        {
            ConstructorInfo constructor = null;
            constructor = TypeDescriptor.GetReflectionType(type).GetConstructor(new Type[0]);
            if (constructor != null)
                return (IComponent) TypeDescriptor.CreateInstance(host, type, new Type[0], new object[0]);

            if (typeof(IComponent).IsAssignableFrom(type))
            {
                constructor = TypeDescriptor.GetReflectionType(type).GetConstructor(BindingFlags.ExactBinding | BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(IContainer) }, null);
                if (constructor != null)
                    return (IComponent) TypeDescriptor.CreateInstance(host, type, new Type[] { typeof(IContainer) }, new object[] { container });
            }

            return null;
        }
    }
}
